﻿using AutoMapper;
using BaseData.API.Write.Applications.Commands;
using BaseData.Domain;
using BaseData.ErrorCode;
using BaseData.Infrastructure.Interfaces;
using MD5Hash;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace BaseData.API.Write.Applications.CommandHandlers
{
    /// <summary>
    /// 修改用户--配置角色 命令
    /// </summary>
    public class UpdUserCommandHandler : IRequestHandler<UpdUserCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<User> userRep;
        private readonly IBaseRepository<Role> roleRep;
        private readonly IBaseRepository<UserRoleRelation> userRoleRep;
        private readonly IMapper mapper;
        private readonly ILogger<UpdUserCommand> logger;

        public UpdUserCommandHandler(IBaseRepository<User> userRep,
            IBaseRepository<Role> roleRep,
            IBaseRepository<UserRoleRelation> userRoleRep,IMapper mapper,
            ILogger<UpdUserCommand> logger) 
        {
            this.userRep = userRep;
            this.roleRep = roleRep;
            this.userRoleRep = userRoleRep;
            this.mapper = mapper;
            this.logger = logger;
        }
        public async Task<ApiResult<int>> Handle(UpdUserCommand request, CancellationToken cancellationToken)
        {

           
            ApiResult<int> result = new ApiResult<int>();
            result.Code=ApiEnum.修改成功;
            result.Message=ApiEnum.修改成功.ToString();

            using (var tran = userRep.DB.Database.BeginTransaction()) 
            {
                try
                {
                    var user = mapper.Map<User>(request);
                    user.CreateTime = DateTime.Now;
                    user.UserPass = request.UserPass.GetMD5();
                    await userRep.UpdateAsync(user);

                    var listSelect = userRoleRep.GetAll().Where(x => x.UserId == request.UserId).ToList();
                    await userRoleRep.DeleteRange(listSelect);
                    var  list = new List<UserRoleRelation>();
                    foreach (var item in request.RoleIds)
                    {
                        list.Add(new UserRoleRelation()
                        {
                            UserId=request.UserId,
                            RoleId=item
                        });
                    }
                    await userRoleRep.AddRange(list);
                    tran.Commit();
                }
                catch (Exception ex)
                {
                    logger.LogError("=>" + ex.Message);
                    result.Code = ApiEnum.修改失败;
                    result.Message = ApiEnum.修改失败.ToString()+ex.Message;
                    tran.Rollback();
                }
            }
            

            return await Task.FromResult(result);
        }
    }
}
